package com.housekeeping.housekeeping.serviceItem.controller;

import com.alibaba.fastjson.JSONObject;
import com.housekeeping.housekeeping.serviceItem.entity.ServiceItemPage;
import com.housekeeping.housekeeping.serviceItem.service.ServiceItemService;
import com.housekeeping.housekeeping.serviceItem.service.impl.ServiceItemServiceImpl;
import com.housekeeping.housekeeping.serviceItem.utils.RequestUtils;
import com.housekeeping.housekeeping.serviceItem.utils.ResponseUtils;
import com.housekeeping.housekeeping.serviceItem.utils.StatUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/ServiceItem/add")
public class ServiceItemAddController extends HttpServlet {
    private ServiceItemService service=new ServiceItemServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String details = req.getParameter("itemDetails");
        String itemPageStr = req.getParameter("itemPage");
        String adminId= RequestUtils.verify(req);
        //非空判断
        if (details==null||itemPageStr==null||adminId==null) { ResponseUtils.fail(resp, StatUtil.PARAMS_VALID); }
        else {
            try {
                //添加限制，一个账户只有个服务项
                  //查询是否已有
                if (service.accountServiceItemExist(adminId)>0){
                    //已存在，限制新增
                    ResponseUtils.fail(resp,StatUtil.SERVICE_ITEM_LIMIT);
                    return;
                }
                ServiceItemPage itemPage = JSONObject.parseObject(itemPageStr, ServiceItemPage.class);
                int res = service.add(adminId,itemPage, details);
                if (res==1){ResponseUtils.success(resp,StatUtil.SUCCESS);}
                else { ResponseUtils.fail(resp,StatUtil.PARAMS_VALID); }
            }catch (Exception e)
            {
                e.printStackTrace();
                ResponseUtils.fail(resp,StatUtil.INTERNET_ERR);
            }
        }
    }

}
